//
//  setLocalnoti.m
//  UIScrollView的快速使用
//
//  Created by hongfei tam on 2019/4/10.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "setLocalnoti.h"

#import "network.h"
#import "MKConstant.h"
#import "DB/DataPersist.h"

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

#define LocalNotiReqIdentifer    @"LocalNotiReqIdentifer"

@interface setLocalnoti (){
    int LocalNotiint;
}

@end

@implementation setLocalnoti

-(void)setnetdataNoti{
    [self cancelLocalNotificaitons2]; //取消所有 通知
    network *sendNetWork = [[network alloc]init];

    NSMutableDictionary *scheduleparams = [DataPersist readValueNSMutableDictionary:@"scheduleparams"];
    [sendNetWork POSTrequest:YOUNGURL type:@"getSchedule" senddic:scheduleparams savekey:@"getSchedule"]; //发送数据
}
- (void)cancelLocalNotificaitons2 {
    NSLog(@"删除所有等待递送的通知");
    
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests]; //删除所有等待递送的通知
        [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];  //删除已经递送的通知
    } else {
        //[[UIApplication sharedApplication] cancelLocalNotification:notify];
    }
    
}


#pragma mark - 设置一条本地推送通知
- (void)setLocalNotification:(NSDictionary *)dic {
    
    NSLog(@"sendLocalNotification -> %@",dic);
    
    NSString *str1 = [dic valueForKey:@"stage"]; //名称
    NSLog(@"str1 : %@",str1 );
    
    NSString *str2 = [dic valueForKey:@"day"];
    NSLog(@"str2 : %@",str2 );
    
    NSString *str3 = [dic valueForKey:@"time"];
    NSLog(@"str3 : %@",str3 );
    
    NSString *notiID = [dic valueForKey:@"id"];
    NSLog(@"notiID : %@",notiID );
    
    NSString *UNNotiID = [NSString stringWithFormat:@"%@%@%@",str2,str3,notiID];
    
    NSString *title = str1;//@"通知-title";
    NSString *subTitle = str2;//@"通知-subtitle";
    NSString *body = str3;//[dic valueForKey:@"task"];//@"通知-body";
    NSInteger badge = 1;
    //NSInteger timeInteval = 5;
    NSString *notiIndexstr = [NSString stringWithFormat:@"%d",LocalNotiint];
    NSDictionary *userInfo = @{@"id":notiID,@"notiIndex":notiIndexstr};//@{@"id":@"LOCAL_NOTIFY_SCHEDULE_ID"};
    
    /**时间设置 */
    //NSString *day = @"2019-03-15";
    NSString *day = str2;//[dic valueForKey:@"day"];
    NSString *year =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(0,4)]];
    NSString *month =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(5,2)]];
    NSString *days =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(8,2)]];
//    NSLog(@"datastr : %@",year );
//    NSLog(@"datastr2 : %@",month );
//    NSLog(@"datastr3 : %@",days );
    
    //NSString *time = @"16:17:00";
    NSString *time = str3;//[dic valueForKey:@"time"];
    NSString *hours =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(0,2)]];
    NSString *minute =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(3,2)]];
    NSString *second =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(6,2)]];
//    NSLog(@"hours : %@",hours );
//    NSLog(@"minute : %@",minute );
//    NSLog(@"second : %@",second );
    
    /* 时间设置 */
    
    if (@available(iOS 10.0, *)) {
        // 1.创建通知内容
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        //[content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"];
        content.sound = [UNNotificationSound defaultSound];
        content.title = title;
        content.subtitle = subTitle;
        content.body = body;
        content.badge = @(badge); //,@"notiIndex":@12
        
        content.userInfo = userInfo;
        
        // 2.设置通知附件内容
        //        NSError *error = nil;
        //        //NSString *path = [[NSBundle mainBundle] pathForResource:@"faphone_BROWN" ofType:@"png"];
        //        //UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"att1" URL:[NSURL fileURLWithPath:path] options:nil error:&error];
        //        if (error) {
        //            NSLog(@"attachment error %@", error);
        //        }
        //content.attachments = @[att];
        content.launchImageName = @"banner_b_1500x420-1-1024x287.jpg";
        // 2.设置声音
        UNNotificationSound *sound = [UNNotificationSound defaultSound]; // [UNNotificationSound soundNamed:@"sound01.wav"];// [UNNotificationSound defaultSound];
        content.sound = sound;
        
        
        
        /*重点开始*/
        // 3.触发模式 定时
        NSDateComponents *components = [[NSDateComponents alloc] init];
        //components.weekday = 4; //周三
        components.year = year.integerValue;
        components.month = month.integerValue;
        components.day = days.integerValue;
        
        components.hour = hours.integerValue; //13点
        components.minute = minute.integerValue;
        components.second = second.integerValue;
        
        
        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
        
        //UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:LocalNotiReqIdentifer content:content trigger:trigger];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:UNNotiID content:content trigger:trigger];
        /*重点结束*/
        
        
        //5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            NSLog(@"5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发,ID : %@",UNNotiID);
        }];
        
    } else {
        //ios 10以下
        
        //        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        //
        //        // 1.设置触发时间（如果要立即触发，无需设置）
        //        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        //        //        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
        //        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];// 5 秒之后
        //
        //        // 2.设置通知标题
        //        localNotification.alertBody = title;
        //
        //        // 3.设置通知动作按钮的标题
        //        localNotification.alertAction = @"查看";
        //
        //        // 4.设置提醒的声音
        //        localNotification.soundName = UILocalNotificationDefaultSoundName;// @"sound01.wav";// UILocalNotificationDefaultSoundName;
        //
        //        // 5.设置通知的 传递的userInfo
        //        localNotification.userInfo = userInfo;
        //
        //        // 6.在规定的日期触发通知
        //        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        //        // 6.立即触发一个通知
        //        //[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
    }
}



//. 管理通知
//iOS10的推送都是通过center进行管理的。通过request的identifier，进行通知的查找、更新、删除。这个标识是用来区分这个通知和其他通知的。
//
//更新：center 的 addNotificationRequest:withCompletionHandler: 方法在 id 不变的情况下重新添加，就可以刷新原有的推送。
//删除：
//
//removePendingNotificationRequestsWithIdentifiers:  //删除特定等待递送的通知
//removeAllPendingNotificationRequests  //删除所有等待递送的通知
//removeDeliveredNotificationsWithIdentifiers:  //删除特定已经递送的通知
//removeAllDeliveredNotifications  //删除已经递送的通知
//
//
//查找：
//
//getPendingNotificationRequestsWithCompletionHandler:  //获取所有等待递送的通知
//getDeliveredNotificationsWithCompletionHandler:  //获取所有已经递送的通知
//
//
//作者：liuyanhongwl
//链接：https://www.jianshu.com/p/bb89d636f989
//来源：简书
//简书著作权归作者所有，任何形式的转载都请联系作者获得授权并注明出处。



-(void)getScheduleAction   //接收信息通知
{
    NSLog(@"接收信息通知");
    [self setScheduleLocalNotification]; //设置本地 日程安排 推送
}

-(void)setScheduleLocalNotification{
    NSMutableArray *Schedulearr = [DataPersist readValueNSMutableArray:@"getSchedule"];
    NSLog(@"Schedulearr循环 : %@" ,Schedulearr);
    
    NSMutableArray *Localnotiarr = [[NSMutableArray alloc]init];
    
    for (NSDictionary *dic in Schedulearr) {
       
        NSString *isset = [dic valueForKey:@"value"];
        if ([isset isEqualToString:@"on"]) {
            
            NSMutableDictionary *newDic = [[NSMutableDictionary alloc]init];
            [newDic setValue:[dic valueForKey:@"stage"] forKey:@"stage"];//名称
//            NSString *str1 = [dic valueForKey:@"stage"];
//            NSLog(@"stage : %@",str1);
            
            [newDic setValue:[dic valueForKey:@"day"] forKey:@"day"];
//            NSString *str2 = [dic valueForKey:@"day"];
//            NSLog(@"day : %@",str2 );
//
            [newDic setValue:[dic valueForKey:@"time"] forKey:@"time"];
//            NSString *str3 = [dic valueForKey:@"time"];
//            NSLog(@"time : %@",str3 );
            
            [newDic setValue:[dic valueForKey:@"id"] forKey:@"id"];
//            NSString *str4 = [dic valueForKey:@"id"];
//            NSLog(@"id : %@",str4 );
            
            [Localnotiarr addObject:newDic];
        }
    }
    
    //NSLog(@"Localnotiarr %@: ",Localnotiarr);

    for (NSDictionary *dic2 in Localnotiarr) {
        NSLog(@"设置本地推送 循环");
        [self setLocalNotification:dic2];
        LocalNotiint = LocalNotiint + 1;
        NSLog(@"LocalNotiint num : %d",LocalNotiint);
    }
    
}

@end
